package components.utils;

import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JTextField;

public class TextFieldVerifier extends CustomVerifier {

    public TextFieldVerifier(String message, JComponent component) {
        super(message, component);
    }

    @Override
    public boolean verify(JComponent input) {
        boolean ret = true;
        if (input instanceof JTextField) {
            JTextField tf = (JTextField) input;
            ret = tf.getText() != null && tf.getText().length() != 0;
        }
        return ret;
    }

    @Override
    public boolean shouldYieldFocus(JComponent input) {
        boolean valueOK;
        
        if (input.isEnabled()) {
            //If the component is enabled, validate the data
            valueOK = verify(input);

            if (input instanceof JTextField) {
                if (!valueOK) {
                    input.setBorder(BorderFactory.createLineBorder(Color.red));
                } else {
                    input.setBorder(null);
                    input.updateUI();
                }
            }
        }
        
        return true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JTextField source = (JTextField)e.getSource();
        shouldYieldFocus(source); //ignore return value
        source.selectAll();
    }
    
}
